package com.scpii.universal.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scpii.universal.Const;
import com.scpii.universal.concurrent.Callback;
import com.scpii.universal.concurrent.ThreadPoolService;
import com.scpii.universal.concurrent.task.GetTask;
import com.scpii.universal.concurrent.task.NativeTask;
import com.scpii.universal.concurrent.task.Task;
import com.scpii.universal.concurrent.task.TaskMsg;
import com.scpii.universal.pb.UniversalProtocol.Cmd;
import com.scpii.universal.pb.UniversalProtocol.FinishTaskSC;

/*
 * 任务处理工具类
 */
public class TaskUtil implements Callback {

	private static final Logger logger = LoggerFactory
			.getLogger(TaskUtil.class);
	/************ Singleton ***********/
	private static TaskUtil instance = new TaskUtil();
	private ThreadPoolService finishTaskPool;
	private ThreadPoolService nativeTaskPool;

	/**
	 * 根据给定大小创建线程池
	 */
	private TaskUtil() {
		finishTaskPool = new ThreadPoolService(
				ThreadPoolService.DEFAULT_POOL_SIZE);
		nativeTaskPool = new ThreadPoolService(
				ThreadPoolService.DEFAULT_POOL_SIZE);
	}

	public static TaskUtil getInstance() {
		return instance;
	}

	public enum TaskMehod {
		GET, NATIVE
	}

	public void sendTask(TaskMehod method, final int action, final byte[] req) {
		TaskMsg msg = new TaskMsg(action, req, this);
		addTask(method, msg);
	}

	private void addTask(TaskMehod method, TaskMsg msg) {
		Task task = null;
		TimeoutThread thread = null;
		switch (method) {
		case GET:
			task = new GetTask(msg);
			thread = new TimeoutThread(task, Const.GETTASK_TIMEOUT);
			finishTaskPool.execute(thread);
			break;
		case NATIVE:
			task = new NativeTask(msg);
			thread = new TimeoutThread(task, Const.NATIVE_TIMEOUT);
			nativeTaskPool.execute(thread);
			break;
		default:
			break;
		}

	}

	@Override
	public boolean handleMessage(int action, byte[] data) {
		boolean isHandle = true;
		try {
			switch (Cmd.valueOf(action)) {
			case GetTask:
				// 本地任务完成 向中间层发送完成通知
				TaskUtil.getInstance().sendTask(TaskMehod.GET,
						Cmd.FinishTask.getNumber(), data);
				break;
			case FinishTask:
				// 从中间层返回的通知
				FinishTaskSC finishTaskSC = FinishTaskSC.parseFrom(data);
				logger.info("从中间层返回的通知:" + finishTaskSC.getOpCode());
				break;
			default:
				isHandle = false;
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isHandle;
	}

	public ThreadPoolService getFinishTaskPool() {
		return finishTaskPool;
	}

	public ThreadPoolService getNativeTaskPool() {
		return nativeTaskPool;
	}

}
